package com.stsdai.portal.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.stsdai.manager.pojo.Shop;
import com.stsdai.manager.pojo.User;
import com.stsdai.portal.util.CookieUtils;
import com.stsdai.portal.util.MsgUtil;
import com.stsdai.sso.service.ShopService;
import com.stsdai.sso.service.UserService;


@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private ShopService shopService;
	
	@Value("${STSD_TICKET}")
	private String STSD_TICKET;
	
	@Value("${STSDAI_SHOP_TICKET}")
	private String STSDAI_SHOP_TICKET;
	
	// http://portal.stsdai.com/user/sendMsg/15101023542?r=0.8945400351311357&callback=jsonp1517455621201&_=1517455670742
	/**
	 * 给用户发送验证码
	 * 
	 * @param telephone
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "sendMsg/{telephone}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> sendMsg(@PathVariable("telephone") String telephone, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		// 生产一个6位随机数作为验证码
		String randomCode = RandomStringUtils.randomNumeric(2) + "0000";
		// 把验证码放到session中
		session.setAttribute(telephone, randomCode);
		// 发送短信
		try {
			MsgUtil.sendSms(telephone, randomCode);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		System.out.println("短信已发送,验证码为:" + randomCode);
		map.put("status", 200);
		return map;
	}
	
	// type : "POST",
	// //url : "/service/user/doRegister",
	// url : "/user/doRegister.html",
	// data : {password:_password,username:_username,phone:_phone,mobileCode:_mobileCode},
	// dataType : 'json',
	// if(result.status == "200")
	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "doRegister", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doRegister(User user, String mobileCode, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		// 从session中取得生成的验证码
		String sessionCode = (String) session.getAttribute(user.getPhone());
		// 验证用户输入得验证码
		if (mobileCode.equals(sessionCode)) {
			this.userService.doRegister(user);
			map.put("status", 200);
		}
		return map;
	}

	// type: "POST",
	// url: "/service/user/doLogin?r=" + Math.random(),
	// data: {username:_username,password:_password},
	// dataType : "json",
	// if (obj.status == 200) {
	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "doLogin", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doLogin(HttpServletRequest request, HttpServletResponse response, User user) {
		// 声明返回的Map对象
		Map<String, Object> map = new HashMap<>();

		// 调用单点登录服务，进行用户登录，返回ticket
		String ticket = this.userService.doLogin(user);

		// 判断ticket是否为非空
		if (StringUtils.isNotBlank(ticket)) {
			// 如果为非空，表示登录成功
			// 需要把ticket放到cookie中
			CookieUtils.setCookie(request, response, this.STSD_TICKET, ticket, 60 * 60 * 24, true);

			// 设置返回数据
			map.put("status", 200);

		}
		// 如果ticket为空，表示登录失败，什么都不用干

		// 返回map
		return map;

	}
	
	@RequestMapping(value = "doShopRegister",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> shopRegister(@CookieValue(value = "STSD_TICKET", defaultValue = "")String ticket, Shop shop){
		// 声明返回的Map对象
		Map<String, Object> map = new HashMap<>();
		User user = this.userService.queryUserByTicket(ticket);
		shop.setId(user.getId());
		shop.setUsername(user.getUsername());
		this.shopService.doShopRegister(shop);
		if(1 == 1){
			map.put("status", 200);
		}
		return map;
	}
	
	@RequestMapping(value = "doShopLogin",method = RequestMethod.GET)
	public String shopLogin(@CookieValue(value = "STSD_TICKET", defaultValue = "")String ticket, HttpServletRequest request, HttpServletResponse response){
		if(StringUtils.isNotBlank(ticket)){
			//通过cookie中的ticket判断用户是否登录
			User user = this.userService.queryUserByTicket(ticket);
			if(user != null){
				//通过shopTicket判断用户是通过验证的卖家
				String shopTicket = this.shopService.doLoginShop(user.getId());
				//是否申请过卖家信息
				if(StringUtils.isNoneBlank(shopTicket)){
					// 需要把shopTicket放到cookie中
					CookieUtils.setCookie(request, response, this.STSDAI_SHOP_TICKET, ticket, 60 * 60 * 24, true);
					//申请中
					if(shopTicket.equals("0")){
						return "redirect:http://shop.stsdai.com/shop/page/index.html";
					//已通过申请
					}else{
						return "redirect:http://shop.stsdai.com/shop/page/index.html";
					}
				}else{
					return "redirect:/page/shop-register.html";
				}
			//没申请过卖家信息,去注册卖家信息
			}
		}
		return "redirect:/page/login.html";
	}

}
